package com.ruicar.afs.cloud.apply.pre.loan.mq.receiver;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseCustAddressDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseCustContactDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseUpdateDetailDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseUpdateInfoSend;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 附条件核准：信审修改客户信息接收
 *
 * @author 耿继辉
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApplyConditionDealProcessor implements AfsMqBizProcessor<CaseUpdateInfoSend> {
    private final ApplyCustContactsService applyCustContactsService;
    private final ApplyCustAddressService applyCustAddressService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyCustPersonalService applyCustPersonalService;
    private final ApplyCarDetailsService applyCarDetailsService;

    /**
     * 报文接收
     *
     * @param entity afs trans entity
     * @return
     * @throws Exception
     */
    @Override
    public boolean processMessage(CaseUpdateInfoSend entity) throws Exception {
        //附条件核准，订单核准数据更新
        if (ObjectUtil.isNotNull(entity)) {
            this.updateData(entity.getCaseUpdateDetailDtoList(), entity.getApplyNo(), entity);
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_APPROVE_CASE_UPDATE_SEND;
    }

    @Override
    public boolean reQueueOnFail() {
        return false;
    }

    /**
     * 解析并更新变更数据至进件库
     *
     * @param caseUpdateDetailDtoList
     */
    public void updateData(List<CaseUpdateDetailDto> caseUpdateDetailDtoList, String applyNo, CaseUpdateInfoSend entity) {
        caseUpdateDetailDtoList.forEach(caseUpdateDetailDto -> {
            //根据客户角色，申请编号查询客户基础信息表信息-进件
            ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(applyNo, caseUpdateDetailDto.getCustRole());
            //将信审传来的客户信息更新入进件库
            this.updateCustPersonalDetails(caseUpdateDetailDto, custBaseInfo);
            log.info("数据交互，申请编号:{},将信审传来的客户信息更新入进件库", applyNo);
            //将信审传来的客户地址信息更新入库
            this.updateCustAddressDetails(caseUpdateDetailDto, custBaseInfo);
            log.info("数据交互，申请编号:{},将信审传来的客户地址信息更新入库", applyNo);
            //主借人联系人更新
            if (ApplyConstants.PRINCIPAL_BORROWER.equals(caseUpdateDetailDto.getCustRole())) {
                //将信审传来的主借人联系人信息更新入库
                this.updateCustContactDetails(caseUpdateDetailDto, custBaseInfo);
                log.info("数据交互，申请编号:{},将信审传来的主借人联系人信息更新入库", applyNo);
            }
            //更新资产信息
            this.updateCarInfo(entity, custBaseInfo);
            log.info("数据交互，申请编号:{},更新资产信息", applyNo);
        });
    }

    /**
     * 更新资产信息
     *
     * @param entity
     * @param custBaseInfo
     */
    public void updateCarInfo(CaseUpdateInfoSend entity, ApplyCustBaseInfo custBaseInfo) {
        //查询资产信息
        ApplyCarDetails carDetailsByApplyNo = applyCarDetailsService.getCarDetailsByApplyNo(custBaseInfo.getApplyNo());
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            carDetailsByApplyNo.setLicenseCity(entity.getLicenseCity());
            carDetailsByApplyNo.setLicenseProvince(entity.getLicenseProvince());
            applyCarDetailsService.updateById(carDetailsByApplyNo);
        }
    }

    /**
     * 更新主借人联系人信息
     *
     * @param caseUpdateDetailDto
     * @param custBaseInfo
     */
    public void updateCustContactDetails(CaseUpdateDetailDto caseUpdateDetailDto, ApplyCustBaseInfo custBaseInfo) {
        ApplyCustContacts custContacts = new ApplyCustContacts();
        //查询主借人联系人信息
        List<ApplyCustContacts> custContactsList = applyCustContactsService.getCustContactsList(custBaseInfo.getApplyNo());
        //删除联系人信息
        custContactsList.forEach(applyCustContactsService::removeById);
        //信审传来的主借人联系人信息
        List<CaseCustContactDto> caseCustContactList = caseUpdateDetailDto.getCaseCustContactList();
        //将信审传来的联系人信息更新入库
        if (CollectionUtil.isNotEmpty(caseCustContactList)) {
            caseCustContactList.forEach(caseCustContactDto -> {
                BeanUtil.copyProperties(caseCustContactDto, custContacts);
                //保存
                applyCustContactsService.save(custContacts);
            });
        }
    }

    /**
     * 更新客户地址信息
     *
     * @param caseUpdateDetailDto
     * @param custBaseInfo
     */
    public void updateCustAddressDetails(CaseUpdateDetailDto caseUpdateDetailDto, ApplyCustBaseInfo custBaseInfo) {
        ApplyCustAddressDetails addressDetails = new ApplyCustAddressDetails();
        //查询进件对应客户的地址信息
        List<ApplyCustAddressDetails> custAddressDetailsList = applyCustAddressService.getCustAddressDetailsList(custBaseInfo.getApplyNo(), custBaseInfo.getId());
        //删除当前客户对应的地址信息
        custAddressDetailsList.forEach(applyCustAddressService::removeById);
        //信审地址
        List<CaseCustAddressDto> caseCustAddressList = caseUpdateDetailDto.getCaseCustAddressList();
        //将信审传来的地址信息保存入进件库
        if (CollectionUtil.isNotEmpty(caseCustAddressList)) {
            caseCustAddressList.forEach(caseCustAddressDto -> {
                BeanUtil.copyProperties(caseCustAddressDto, addressDetails);
                //保存
                applyCustAddressService.save(addressDetails);
            });
        }
    }

    /**
     * 更新客户明细信息
     *
     * @param custBaseInfo        申请编号
     * @param caseUpdateDetailDto 信审客户信息报文
     */
    public void updateCustPersonalDetails(CaseUpdateDetailDto caseUpdateDetailDto, ApplyCustBaseInfo custBaseInfo) {
        //根据客户id查询对应客户的明细
        ApplyCustPersonalDetail custPersonalDetail = applyCustPersonalService.getCustPersonalDetail(custBaseInfo.getApplyNo(), custBaseInfo.getId());
        custPersonalDetail.setDrivingType(caseUpdateDetailDto.getDrivingType());
        custPersonalDetail.setTotalIncome(caseUpdateDetailDto.getFamilyIncome());
        custPersonalDetail.setDrivingLicenceNo(caseUpdateDetailDto.getDrivingLicenceNo());
        custPersonalDetail.setHighestEducation(caseUpdateDetailDto.getHighestEducation());
        custPersonalDetail.setIndustryType(caseUpdateDetailDto.getIndustryType());
        custPersonalDetail.setMaritalStatus(caseUpdateDetailDto.getMaritalStatus());
        custPersonalDetail.setOutstandingLoan(caseUpdateDetailDto.getOutstandingLoan());
        custPersonalDetail.setPosition(caseUpdateDetailDto.getPosition());
        custPersonalDetail.setProfessional(caseUpdateDetailDto.getProfessionalType());
        custPersonalDetail.setMonthlyIncome(caseUpdateDetailDto.getMonthlyIncome());
        custPersonalDetail.setTotalIncome(caseUpdateDetailDto.getFamilyIncome());
        custPersonalDetail.setUnitName(caseUpdateDetailDto.getUnitName());
        custPersonalDetail.setCompanyPhone(caseUpdateDetailDto.getUnitTelPhone());
        custPersonalDetail.setUnitNature(caseUpdateDetailDto.getUnitType());
        custPersonalDetail.setWorkAge(caseUpdateDetailDto.getWorkAge());
        //更新
        applyCustPersonalService.updateById(custPersonalDetail);
    }
}
